<template>
  <div class="chart-bar-memory-root">
    <div class="memory-chart" ref="ChartBarMemoryRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useDark } from '@vueuse/core';
// echarts
import * as echartTheme from '@/assets/styles/xz/echartTheme';
import * as echarts from "echarts/core";
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
import { BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([TitleComponent, TooltipComponent, GridComponent, LegendComponent, BarChart, CanvasRenderer]);

const isDark = useDark();

const ChartBarMemoryRef = ref<any>(null);
let chartBarMemory: any;
let chartData: any;

const initMap = (info: any) => {
  chartData = []
  chartData.push({
    value: info.used_memory,
    value_human: info.used_memory_human
  });
  chartData.push({
    value: info.used_memory_peak,
    value_human: info.used_memory_peak_human
  });
  renderChart();
}

const renderChart = () => {
  chartBarMemory.setOption({
    tooltip: {
      ...echartTheme.tooltip(), ...{
        formatter: (params: any) => {
          return "<div style='text-align: left'>" +
            params[0].name + "<br/>" +
            "大小：" + params[0].data.value_human + "<br/>" +
            "</div>"
        }
      }
    },
    grid: { top: '10px', left: '10px', right: '10px', bottom: '0', containLabel: true },
    xAxis: {
      type: 'value', axisLabel: { interval: 0, rotate: 10, fontWeight: 700 },
      splitLine: { lineStyle: { color: [echartTheme.common().axisLineColor] } }
    },
    yAxis: {
      type: 'category', axisLabel: { interval: 0, rotate: 90, fontWeight: 700 }, data: ['当前内存', '峰值内存'],
    },
    series: [
      {
        type: 'bar',
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold',
          fontFamily: 'Consolas,Monaco',
          color: !isDark.value ? '#c2c2c2' : '#D3D3D3',
          formatter: (params: any) => {
            return params.data.value_human
          }
        },
        itemStyle: {
          color: !isDark.value ? '#aa4d45' : '#914840'
        },
        data: chartData
      }
    ]
  })
}

onMounted(() => {
  chartBarMemory = echarts.init(ChartBarMemoryRef.value);
  chartBarMemory.resize();
})

defineExpose({
  initMap
})
</script>

<style scoped lang="scss">
.chart-bar-memory-root {

  .memory-chart {
    @include box(100%, 100%);
  }
}
</style>
